<?php

namespace app\apishop\controller;

use app\admin\model\cases\Ctype;
use app\apishop\validate\ComplaintValidate;
use app\common\controller\Api;
use think\Config;
use think\Exception;

/**
 * 商户投诉信息表
 */
class Complaint extends Api
{

    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    protected $failException = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\shop\Complaint();
        $this->modelType = new Ctype();
        $this->modelUser = new \app\admin\model\shop\User();
        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }


    /**
     * 列表
     * @return void
     */
    public function list()
    {
        $input = input();
        $id = $this->auth->getUserinfo(2)['id'];
        try {
            $pageArr = [
                'page' => 1,
                'page_limit' => 30,
            ];
            $where['shop_id'] = $id;
            if (!empty($input['id'])) {
                $where['id'] = $input['id'];
            }
            $pageArr = array_merge($pageArr, $input);
            $data = $this->model->where($where)
                ->order('id desc')
                ->field('id,cases_type_id,
                user_shop_id,title,content,image,videofile,status,refuse,type
                ')
                ->paginate(['page' => $pageArr['page'] ?: 1, 'list_rows' => $pageArr['page_limit'] ?: 10]);
            foreach ($data->items() as &$v) {
                $v->cases_type_name = $this->modelType->where('id', $v['cases_type_id'])->value('name') ?? '';
                $v->user_shop_info = $this->modelUser->alias('m')
                    ->join('user_shop_class d', 'd.id=m.user_shop_class_id')
                    ->where('m.id', $v->user_shop_id)
                    ->field('m.name,m.coverimage,m.city,m.merchant_address,d.name as type_name')
                    ->find();
            }
            $this->success('ok', $data);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }


    /**
     * 投诉
     * @return void
     */
    public function submit()
    {
        $input = input('post.');
        $userinfo = $this->auth->getUserinfo(2);
        try {
            $this->validate($input, ComplaintValidate::class . '.submit');
            $input['shop_id'] = $userinfo['id'];
            $input['username_mobile'] = $userinfo['mobile'];
            $input['username'] = $userinfo['username'];
            $this->model->insert($input);
            $this->success('投诉成功');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }


}